package com.epam.facebook_client.fragment;

import java.util.HashMap;
import java.util.Map;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.epam.facebook_client.ProfileActivity;
import com.epam.facebook_client.R;
import com.epam.facebook_client.content.contract.AppContract;
import com.epam.facebook_client.manager.ImageManager;
import com.epam.facebook_client.processor.FriendsProcessor;
import common.adapters.AbstractCursorAdapter;
import common.processor.IProcessor;
import common.utils.StateNetworkUtil;

public class FriendsListFragment extends BaseServiceFragment implements LoaderCallbacks<Cursor> {

	private static final String TAG = FriendsListFragment.class.getSimpleName();

	private ImageManager imageManager;
	private ListView friendsListView;
	private ProgressBar progressBar;
	private boolean dualPane;

	private static final int FRIENDS_LOAD = 0;

	private AbstractCursorAdapter adapter;

	private int requestId;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View inflate = inflater.inflate(R.layout.activity_friends_list, container, false);
		friendsListView = (ListView) inflate.findViewById(R.id.listFriends);
		progressBar = (ProgressBar) inflate.findViewById(R.id.progressBar);
		imageManager = ImageManager.get(getActivity());
		setHasOptionsMenu(true);

		friendsListView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				show(String.valueOf(id));
			}
		});
		return inflate;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		getLoaderManager().initLoader(FRIENDS_LOAD, savedInstanceState, this);
		View profile = getActivity().findViewById(R.id.friendsProfileLayout);
		dualPane = profile != null && profile.getVisibility() == View.VISIBLE;
	}

	private void show(String id) {
		if (dualPane) {
			ProfileFragment pActivity = ProfileFragment.newInstance(id);
			FragmentTransaction ft = getFragmentManager().beginTransaction();
			ft.replace(R.id.friendsProfileLayout, pActivity);
			ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
			ft.commit();
		} else {
			Intent intent = new Intent(getActivity(), ProfileActivity.class);
			intent.putExtra("id", id);
			startActivity(intent);
		}
	}

	private void startServiceHelper(Map<String, String> parameter) {
		if (StateNetworkUtil.isOnline(getActivity())) {
			if (getServiceHelper().isPending(requestId)) {
				return;
			}
			requestId = getServiceHelper().startService(FriendsProcessor.ACTION, parameter);
		} else {
			Toast.makeText(getActivity(), "No connection to Internet", Toast.LENGTH_LONG).show();
		}
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		MenuItem refresh = menu.add(getString(R.string.menu_refresh));
		refresh.setOnMenuItemClickListener(new OnMenuItemClickListener() {
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				progressBar.setVisibility(View.VISIBLE);
				Map<String, String> parameter = new HashMap<String, String>(1);
				parameter.put(IProcessor.EXTRA_EXECUTE_METHOD, IProcessor.METHOD_GET);
				startServiceHelper(parameter);
				return true;
			}
		});
		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle bundle) {
		progressBar.setVisibility(View.VISIBLE);
		String[] projection = { AppContract.FriendsColumns._ID, AppContract.FriendsColumns.NAME,
				AppContract.FriendsColumns.PICTURE };
		CursorLoader cursor = new CursorLoader(getActivity(), AppContract.FriendsColumns.CONTENT_URI,
				projection, null, null, AppContract.FriendsColumns.SORT_ORDER_DEFAULT);
		return cursor;
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
		if (cursor.getCount() > 0) {
			progressBar.setVisibility(View.GONE);
			String[] columnNames = { AppContract.FriendsColumns.NAME, AppContract.FriendsColumns.PICTURE };
			int[] viewId = { R.id.friendName, R.id.friendImage };
			adapter = new AbstractCursorAdapter(getActivity(), cursor, imageManager, viewId, columnNames) {

				@Override
				public int getLayoutAdapterId() {
					return R.layout.adapter_friends_list_item;
				}

				@Override
				public void setImageNull(ImageView imageView) {
					imageView.setVisibility(View.GONE);
				}
			};
			friendsListView.setAdapter(adapter);
		} else {
			Map<String, String> parameter = new HashMap<String, String>(1);
			parameter.put(IProcessor.EXTRA_EXECUTE_METHOD, IProcessor.METHOD_GET);
			startServiceHelper(parameter);
		}
	}

	@Override
	public void onLoaderReset(Loader<Cursor> loader) {

	}

	@Override
	public void onServiceResult(int requestId, Intent requestIntent, int resultCode, Bundle resultData) {
		progressBar.setVisibility(View.GONE);
		switch (resultCode) {
		case IProcessor.RESULT_OK:
			break;
		case IProcessor.RESULT_ERROR:
			Exception e = (Exception) resultData.getSerializable(IProcessor.EXTRAS_ERROR);
			Log.e(TAG, "ERROR: " + e);
			Toast.makeText(getActivity(), "ERROR: " + e.getMessage(), Toast.LENGTH_SHORT).show();
			break;

		default:
			break;
		}
	}
}